﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Centny
{

    public class NotificationCenter
    {
        public delegate void ReceiveNotice(String name, Object data);
        private static NotificationCenter _Deafult = new NotificationCenter();
        public static NotificationCenter Default
        {
            get
            {
                return _Deafult;
            }
        }

        private Dictionary<String, List<ReceiveNotice>> _OnReceiveNotice = new Dictionary<String, List<ReceiveNotice>>();
        public void AddListener(String name, ReceiveNotice rn)
        {
            lock (this._OnReceiveNotice)
            {
                List<ReceiveNotice> rns;
                if (this._OnReceiveNotice.ContainsKey(name))
                {
                    rns = this._OnReceiveNotice[name];
                }
                else
                {
                    rns = new List<ReceiveNotice>();
                }
                rns.Add(rn);
                this._OnReceiveNotice[name] = rns;
            }
        }
        public void RemoveListener(String name, ReceiveNotice rn)
        {
            lock (this._OnReceiveNotice)
            {
                
                if (!this._OnReceiveNotice.ContainsKey(name))
                {
                    return;
                }
                List<ReceiveNotice> rns = this._OnReceiveNotice[name];
                rns.Remove(rn);
                this._OnReceiveNotice[name] = rns;
            }
        }
        public async void Send(String name, Object data = null)
        {
            lock (this._OnReceiveNotice)
            {
                if (!this._OnReceiveNotice.ContainsKey(name))
                {
                    return;
                }
            }
            await Task.Delay(10);
            lock (this._OnReceiveNotice)
            {
                List<ReceiveNotice> rns = this._OnReceiveNotice[name];
                foreach (ReceiveNotice rn in rns)
                {
                    rn(name, data);
                }
            }
        }
    }
}
